package com.newer.textdbnotepad

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.newer.textdbnotepad.databinding.NoteItemViewBinding
import com.newer.textdbnotepad.sdk.NoteInfo

class NoteAdapter() : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private val notes = mutableListOf<NoteInfo>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return NoteItemViewBinding.inflate(LayoutInflater.from(parent.context), parent, false)
            .let { object : RecyclerView.ViewHolder(it.root) {} }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val note = notes[position]
        val binding = NoteItemViewBinding.bind(holder.itemView)
        binding.tvTitle.text = note.noteTitle

        binding.root.setOnClickListener {
            NoteDetailActivity.launch(it.context, note.noteKey)
        }
    }

    override fun getItemCount() = notes.size

    @SuppressLint("NotifyDataSetChanged")
    fun setNotes(notes: List<NoteInfo>) {
        this.notes.clear()
        this.notes.addAll(notes)
        notifyDataSetChanged()
    }

}
